package com.test.bat;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ShutdownHook implements Runnable {
	public ShutdownHook() {
		// register a shutdown hook for this class.
		// a shutdown hook is an initialzed but not started thread, which will
		// get up and run
		// when the JVM is about to exit. this is used for short clean up tasks.
		Runtime.getRuntime().addShutdownHook(new Thread(this));
		System.out.println(">>> shutdown hook registered");
	}

	// this method will be executed of course, since it's a Runnable.
	// tasks should not be light and short, accessing database is alright
	// though.
	public void run() {
		System.out.println("\n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
		this.cleanUp();
		System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");
		log("Clean finished.");
	}

	// (-: a very simple task to execute
	private void cleanUp() {
		for (int i = 0; i < 7; i++) {
			System.out.println(i);
		}
		try {
			TimeUnit.SECONDS.sleep(10);
		} catch (InterruptedException e) {
		}
	}

	private void log(String msg) {
		File f = new File("E:/apps/mytestapp2010/bin/log.txt");
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(f));
			out.write(msg);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {

		new ShutdownHook();

		System.out.println(">>> Sleeping for 5 seconds, try ctrl-C now if you like.");
		
		System.exit(1);

		try {
			Thread.sleep(9000); // (-: give u the time to try ctrl-C
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}

		System.out.println(">>> Slept for 10 seconds and the main thread exited.");
	}
}
